package com.attendance.www.hr.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.actionsoft.bpms.api.OpenApiClient;
import com.attendance.www.hr.beans.BMPBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.ApprovalRecordMapper;
import com.attendance.www.hr.dao.mapper.AttendanceMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.entitys.ApprovalRecord;
import com.attendance.www.hr.entitys.Attendance;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.Request;
import com.attendance.www.hr.entitys.Retroactive;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IBpmService;
import com.attendance.www.hr.utils.JsonDateValueProcessor;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Service
public class BpmServiceImpl implements IBpmService {
	
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private ApprovalRecordMapper approvalRecordDao;
	@Resource
	private AttendanceMapper attendanceDao;
	
	private Logger log = Logger.getLogger(BpmServiceImpl.class);
	
	//请求等待时间
	private int time=90000;

	/**
	 * 申请请求BPM平台接口
	 * @param request
	 * @param employeeId
	 * @param interfaceType
	 */
	@SuppressWarnings("static-access")
	@Override
	public void openApplyBPM(Request request,Retroactive retroactive,Integer employeeId,String interfaceType) {
		//初始化JSON日期类			
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		
		BMPBean bpm=new BMPBean();
		//格式化申请日期
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String requestDateStr = null;
		
		if(request!=null) {
			//类反射
			BeanUtils.copyProperties(request, bpm);
		    requestDateStr = formatter.format(request.getRequestDate());
		}
		
		if(retroactive!=null) {
			//类反射
			BeanUtils.copyProperties(retroactive, bpm);
			requestDateStr = formatter.format(retroactive.getRetroactiveDate());
			bpm.setRequestId(retroactive.getRetroactiveId());
			bpm.setRetroactiveStartTime(retroactive.getStartTime());
			bpm.setRetroactiveEndTime(retroactive.getEndTime());
			bpm.setRequestType(15);
			//通话考勤补签中的考勤表ID查询考勤日期
			Attendance attendance=attendanceDao.selectByPrimaryKey(retroactive.getAttendanceId());
			bpm.setRetroactiveDate(attendance.getAttendanceDate());
		}
		
		//查询申请人员工号
		Employee employee=employeeDao.selectByPrimaryKey(employeeId);
		bpm.setEmployeeNo(employee.getEmployeeNo());
		
		//设置参数
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("InterfaceType",interfaceType);
		args.put("userId","");                                                                                                                                                              
		args.put("title","");             
		args.put("applyNo","");  
		//格式化CLASS类为JSON格式
		JSONObject params = new JSONObject();
		params=params.fromObject(bpm,jsonConfig);
		params.put("requestDate", requestDateStr);
		//获取字符串JSON格式
		String dataJson=params.toString(); 
		args.put("dataJson",dataJson.toUpperCase());                                                                                                           
		args.put("dataSubJson",""); 
		//请求地址
		OpenApiClient client=new OpenApiClient(AppConstant.BPM_REQUEST_URL,
												AppConstant.BPM_REQUEST_ACCESSKEY, 
												AppConstant.BPM_REQUEST_SECRET, 
												null, 
												time, 
												time);
		try {
			//请求接口方法
			String str=client.exec(AppConstant.BPM_REQUEST_APPLY_INTERFACE, args);
			log.error("读取BPM接口返回值：" + "==>" + str);
			params=params.fromObject(str);
			String result=params.getJSONObject("data").getString("result");
			//请求接口方法错误
			if(result==null
					|| result.equals("0")) {
				log.error("读取BPM接口返回内容错误：" + "==>" + result);
				throw new ResultFaultException("0_00042");
			}
			
			//添加审批记录表信息
			ApprovalRecord approvalRecord=new ApprovalRecord();
			if(request!=null) {
				approvalRecord.setRequestId(request.getRequestId());
			}
			if(retroactive!=null) {
				approvalRecord.setRetroactiveId(retroactive.getRetroactiveId());
			}
			approvalRecord.setIsApprove(1);
			approvalRecordDao.insertSelective(approvalRecord);
			
		}catch (Exception e) {
			log.error("请求BPM接口错误：" + "==>" + e.getMessage());
			log.error(e,e);
			throw new ResultFaultException("0_00042");
		}
	}
	
	/**
	 * 撤销申请接口
	 * @param request
	 * @param retroactive
	 * @param employeeId
	 * @param interfaceType
	 */
	@SuppressWarnings("static-access")
	public boolean revokeBPM(Request request,Retroactive retroactive,Integer employeeId,String interfaceType) {
		//初始化JSON日期类			
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		//格式化申请日期
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String requestDateStr = null;
		
		JSONObject params = new JSONObject();
		BMPBean bpm=new BMPBean();
		if(request!=null) {
			//类反射
			BeanUtils.copyProperties(request, bpm);
			requestDateStr = formatter.format(request.getRequestDate());
		}
		if(retroactive!=null) {
			//类反射
			BeanUtils.copyProperties(retroactive, bpm);
			requestDateStr = formatter.format(retroactive.getRetroactiveDate());
			bpm.setRequestId(retroactive.getRetroactiveId());
			bpm.setRetroactiveStartTime(retroactive.getStartTime());
			bpm.setRetroactiveEndTime(retroactive.getEndTime());
			bpm.setRequestType(15);
			//通话考勤补签中的考勤表ID查询考勤日期
			Attendance attendance=attendanceDao.selectByPrimaryKey(retroactive.getAttendanceId());
			bpm.setRetroactiveDate(attendance.getAttendanceDate());
		}
		//查询申请人员工号
		Employee employee=employeeDao.selectByPrimaryKey(employeeId);
		bpm.setEmployeeNo(employee.getEmployeeNo());
		
		//设置参数
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("InterfaceType",interfaceType);
		args.put("userId","");                                                                                                                                                              
		args.put("title","");             
		if(request!=null) {
			args.put("applyNo",request.getRequestId());  
		}
		if(retroactive!=null) {
			args.put("applyNo",retroactive.getRetroactiveId());  
		}
		/*args.put("applyNo",""); 
		params=params.fromObject(bpm,jsonConfig);
		params.put("requestDate", requestDateStr);
		//获取字符串JSON格式
		String dataJson=params.toString(); 
		args.put("dataJson",dataJson.toUpperCase());                                                                                                           
		args.put("dataSubJson",""); */
		//请求地址
		OpenApiClient client=new OpenApiClient(AppConstant.BPM_REQUEST_URL,
											   AppConstant.BPM_REQUEST_ACCESSKEY,
											   AppConstant.BPM_REQUEST_SECRET,
											   null,
											   time,
											   time);
		try {
			//请求接口方法
			String str=client.exec(AppConstant.BPM_REQUEST_REVOKE_INTERFACE, args);
			log.error("撤销BPM接口返回值：" + "==>" + str);
			params=params.fromObject(str);
			String result=params.getJSONObject("data").getString("result");
			//请求接口方法错误
			if(result==null) {
				throw new ResultFaultException("0_00044");
			}else if(result.equals("0")) {
				throw new ResultFaultException("0_00043");
			}
		}catch (Exception e) {
			log.error("撤销BPM接口失败：" + "==>" + e.getMessage());
			log.error(e,e);
			throw new ResultFaultException("0_00044");
		}
		return true;
	}
}
